<template>
  <div class="inspection-container">
    <el-card class="inspection-card">
      <template #header>
        <div class="card-header">
          <h3>宿舍卫生检查管理</h3>
          <div class="header-options">
            <el-checkbox v-model="onlyShowMine" @change="handleFilterChange">查看我的检查</el-checkbox>
            <el-button type="primary" @click="showAddDialog">新增检查记录</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索过滤 -->
      <div class="filter-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="楼栋号">
            <el-input v-model="searchForm.loudong" placeholder="请输入楼栋号" clearable></el-input>
          </el-form-item>
          <el-form-item label="宿舍号">
            <el-input v-model="searchForm.sushe" placeholder="请输入宿舍号" clearable></el-input>
          </el-form-item>
          <el-form-item label="检查时间">
            <el-date-picker
              v-model="searchForm.jianchashijian"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              clearable
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 检查记录列表 -->
      <el-table
        v-loading="loading"
        :data="inspectionList"
        style="width: 100%"
        border
      >
        <el-table-column prop="jianchabianhao" label="检查编号" width="180"></el-table-column>
        <el-table-column prop="loudong" label="楼栋号" width="100"></el-table-column>
        <el-table-column prop="sushe" label="宿舍号" width="100"></el-table-column>
        <el-table-column prop="jianchapingfen" label="检查评分" width="100">
          <template #default="scope">
            <el-tag :type="getScoreTagType(scope.row.jianchapingfen)">{{ scope.row.jianchapingfen }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="jianchashijian" label="检查时间" width="120"></el-table-column>
        <el-table-column prop="suguanxingming" label="宿管" width="120"></el-table-column>
        <el-table-column prop="beizhu" label="备注" min-width="180"></el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="handleEdit(scope.row)"
              v-if="canEdit(scope.row)"
            >编辑</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
              v-if="canEdit(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="limit"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增检查记录' : '编辑检查记录'"
      width="50%"
      destroy-on-close
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="检查编号" prop="jianchabianhao">
          <el-input v-model="form.jianchabianhao" :disabled="dialogType === 'edit'" placeholder="自动生成"></el-input>
        </el-form-item>
        <el-form-item label="楼栋号" prop="loudong">
          <el-input v-model="form.loudong" placeholder="请输入楼栋号"></el-input>
        </el-form-item>
        <el-form-item label="宿舍号" prop="sushe">
          <el-input v-model="form.sushe" placeholder="请输入宿舍号"></el-input>
        </el-form-item>
        <el-form-item label="检查评分" prop="jianchapingfen">
          <el-input-number v-model="form.jianchapingfen" :min="0" :max="100"></el-input-number>
        </el-form-item>
        <el-form-item label="检查时间" prop="jianchashijian">
          <el-date-picker
            v-model="form.jianchashijian"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="宿管" prop="suguanxingming">
          <el-input v-model="form.suguanxingming" disabled placeholder="自动填充"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="beizhu">
          <el-input v-model="form.beizhu" type="textarea" :rows="3" placeholder="请输入备注内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 数据列表
const inspectionList = ref([])
const loading = ref(false)
const total = ref(0)
const page = ref(1)
const limit = ref(10)
const onlyShowMine = ref(true) // 默认只查看自己的检查记录

// 对话框控制
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' or 'edit'
const formRef = ref(null)

// 当前登录用户信息
const currentUser = reactive({
  username: localStorage.getItem('adminName') || '',
  name: '', // 宿管姓名
  loudong: '', // 宿管楼栋号
  role: localStorage.getItem('role') || ''
})

// 搜索表单
const searchForm = reactive({
  loudong: '',
  sushe: '',
  jianchashijian: ''
})

// 表单数据
const form = reactive({
  id: '',
  jianchabianhao: '',
  loudong: '',
  sushe: '',
  jianchapingfen: 80,
  jianchashijian: '',
  suguanxingming: '',
  beizhu: ''
})

// 表单验证规则
const rules = {
  loudong: [{ required: true, message: '请输入楼栋号', trigger: 'blur' }],
  sushe: [{ required: true, message: '请输入宿舍号', trigger: 'blur' }],
  jianchapingfen: [{ required: true, message: '请输入检查评分', trigger: 'blur' }],
  jianchashijian: [{ required: true, message: '请选择检查时间', trigger: 'change' }],
  suguanxingming: [{ required: true, message: '宿管姓名不能为空', trigger: 'blur' }]
}

// 初始化加载数据
onMounted(async () => {
  console.log('组件挂载，当前用户信息:', currentUser)
  
  // 先加载用户信息
  await loadUserInfo()
  
  // 确保用户信息加载后再获取检查记录
  console.log('加载用户信息完成，开始获取检查记录, 用户名:', currentUser.username, '姓名:', currentUser.name)
  getInspectionList()
})

// 加载当前用户信息
const loadUserInfo = async () => {
  try {
    // 获取并输出完整的用户信息
    console.log('当前localStorage内容:', {
      adminName: localStorage.getItem('adminName'),
      role: localStorage.getItem('role'),
      token: localStorage.getItem('Token') ? '存在' : '不存在'
    })
    
    // 获取当前登录的宿管账号
    currentUser.username = localStorage.getItem('adminName') || ''
    currentUser.role = localStorage.getItem('role') || ''
    
    console.log('解析后的用户信息:', currentUser)
    
    // 检查用户是否登录
    if (!currentUser.username) {
      throw new Error('用户未登录，请先登录')
    }
    
    // 先尝试不判断角色，针对当前登录用户获取宿管信息
    console.log('开始加载宿管信息，当前账号:', currentUser.username)
    
    // 使用当前账号查询宿管完整信息，重点获取宿管姓名
    const response = await axios.get(`/springbootyyh3w/suguan/list`, {
      params: {
        // 精确匹配宿管账号
        suguanzhanghao: currentUser.username,
        // 只需要一条记录
        page: 1,
        limit: 1
      },
      headers: {
        'Token': localStorage.getItem('Token')
      }
    })
    
    console.log('宿管信息查询响应:', response.data)
    
    // 检查是否成功获取宿管信息
    if (response.data.code === 0 && response.data.data && response.data.data.list && response.data.data.list.length > 0) {
      // 从返回的列表中获取宿管信息（通常只有一条记录）
      const suguanInfo = response.data.data.list[0]
      
      // 输出完整的宿管信息以便调试
      console.log('获取到的宿管信息:', suguanInfo)
      
      // 确保姓名字段不为空
      if (!suguanInfo.suguanxingming) {
        throw new Error('宿管姓名字段为空，请联系系统管理员修改宿管信息')
      }
      
      // 设置宿管姓名
      currentUser.name = suguanInfo.suguanxingming
      
      // 设置楼栋号
      currentUser.loudong = suguanInfo.loudong || ''
      
      console.log('成功获取宿管信息 - 姓名:', currentUser.name, '楼栋号:', currentUser.loudong)
    } else {
      // 如果没有找到宿管信息，可能是系统中没有该宿管，或者当前用户不是宿管
      // 降级处理：使用当前账号作为姓名
      console.warn('未找到对应宿管信息，将使用当前账号作为姓名')
      currentUser.name = currentUser.username
    }
  } catch (error) {
    console.error('获取宿管信息失败:', error)
    // 显示错误消息
    ElMessage.error(`获取宿管信息失败: ${error.message || '未知错误'}`)
    // 降级处理：使用当前账号作为姓名
    currentUser.name = currentUser.username || '未知用户'
    console.log('错误降级处理，使用账号作为姓名:', currentUser.name)
  }
}

// 获取检查记录列表
const getInspectionList = async () => {
  loading.value = true
  try {
    // 确保在查询前已经获取了宿管姓名
    if (onlyShowMine.value && (!currentUser.name || currentUser.name === '')) {
      try {
        // 如果需要筛选且没有宿管姓名，尝试重新获取
        await loadUserInfo()
        console.log('已重新加载宿管信息:', currentUser.name)
      } catch (error) {
        console.warn('获取宿管信息失败，可能无法正确筛选记录')
      }
    }
    
    const params = {
      page: page.value,
      limit: limit.value,
      // 添加onlyShowMine参数，将布尔值转为字符串传递
      onlyShowMine: onlyShowMine.value.toString()
    }
    
    // 仅当有搜索条件时才添加
    if (searchForm.loudong) {
      params.loudong = searchForm.loudong
    }
    
    if (searchForm.sushe) {
      params.sushe = searchForm.sushe
    }
    
    if (searchForm.jianchashijian) {
      // 根据后端MPUtil.between方法的要求，日期参数应该使用字段名_start或字段名_end格式
      // 对于单个日期，我们设置jianchashijian_start和jianchashijian_end为同一天
      params["jianchashijian_start"] = searchForm.jianchashijian
      params["jianchashijian_end"] = searchForm.jianchashijian
      console.log('设置日期范围查询:', searchForm.jianchashijian)
    }
    
    // 如果选择"查看我的检查"且知道宿管姓名，直接在前端添加筛选条件
    // 这样即使后端处理有问题，前端也能确保正确筛选
    if (onlyShowMine.value && currentUser.name) {
      params.suguanxingming = currentUser.name
      console.log('添加宿管姓名筛选:', currentUser.name)
    }
    
    console.log('获取检查记录 - 参数:', JSON.stringify(params))
    
    const response = await axios.get('/springbootyyh3w/weishengjiancha/page', {
      params,
      headers: {
        'Token': localStorage.getItem('Token')
      }
    })
    
    console.log('API响应:', JSON.stringify(response.data))
    
    if (response.data.code === 0) {
      inspectionList.value = response.data.data.list
      total.value = response.data.data.total
      console.log('检查记录数据更新:', inspectionList.value.length, '条记录')
    } else {
      ElMessage.error('获取检查记录失败')
    }
  } catch (error) {
    console.error('获取检查记录出错', error)
    ElMessage.error('获取检查记录出错')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  getInspectionList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.loudong = ''
  searchForm.sushe = ''
  searchForm.jianchashijian = ''
  page.value = 1
  getInspectionList()
}

// 筛选变化处理
const handleFilterChange = () => {
  page.value = 1
  getInspectionList()
}

// 显示添加对话框
const showAddDialog = async () => {
  try {
    // 先加载用户信息，确保获取到正确的宿管姓名
    await loadUserInfo()
  } catch (error) {
    // loadUserInfo中的错误已经显示了错误消息
    console.warn('加载用户信息出错，将使用默认信息继续')
    // 这里不再抛出异常，让流程继续
  }
  
  dialogType.value = 'add'
  form.id = ''
  form.jianchabianhao = `WS${Date.now()}`
  form.loudong = currentUser.loudong || '' // 默认设置当前宿管的楼栋号
  form.sushe = ''
  form.jianchapingfen = 80
  form.jianchashijian = new Date().toISOString().split('T')[0]
  form.suguanxingming = currentUser.name || ''
  form.beizhu = ''
  
  console.log('打开添加对话框，表单数据:', JSON.stringify(form))
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.id = row.id
  form.jianchabianhao = row.jianchabianhao
  form.loudong = row.loudong || ''
  form.sushe = row.sushe
  form.jianchapingfen = row.jianchapingfen
  form.jianchashijian = row.jianchashijian
  form.suguanxingming = row.suguanxingming
  form.beizhu = row.beizhu
  dialogVisible.value = true
}

// 判断是否可以编辑/删除（只有创建记录的宿管可以编辑删除）
const canEdit = (row) => {
  if (!row || !row.suguanxingming) {
    console.warn('记录或宿管姓名字段为空，无法判断编辑权限')
    return false
  }
  
  if (!currentUser.name) {
    console.warn('当前用户宿管姓名未设置，无法判断编辑权限')
    return false
  }
  
  const hasPermission = row.suguanxingming === currentUser.name
  
  if (hasPermission) {
    console.log(`记录ID:${row.id} 有编辑权限，宿管姓名匹配: ${row.suguanxingming} === ${currentUser.name}`)
  } else {
    console.log(`记录ID:${row.id} 无编辑权限，宿管姓名不匹配: ${row.suguanxingming} !== ${currentUser.name}`)
  }
  
  return hasPermission
}

// 提交表单前检查必填字段并补充
const prepareFormData = () => {
  // 确保检查编号存在
  if (!form.jianchabianhao) {
    form.jianchabianhao = `WS${Date.now()}`
  }
  
  return form
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const url = dialogType.value === 'add' 
          ? '/springbootyyh3w/weishengjiancha/add' 
          : '/springbootyyh3w/weishengjiancha/update'
        
        // 准备表单数据
        const formData = prepareFormData()
        console.log('提交的表单数据：', JSON.stringify(formData))
        
        const response = await axios.post(url, formData, {
          headers: {
            'Token': localStorage.getItem('Token'),
            'Content-Type': 'application/json'
          }
        })
        
        console.log('提交响应：', response.data)
        
        if (response.data.code === 0) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
          dialogVisible.value = false
          // 手动延迟重新加载数据，确保数据库操作完成
          setTimeout(() => {
            getInspectionList()
          }, 500)
        } else {
          ElMessage.error(response.data.msg || (dialogType.value === 'add' ? '添加失败' : '更新失败'))
        }
      } catch (error) {
        console.error('提交表单出错', error)
        // 显示详细错误信息
        if (error.response) {
          console.error('错误响应数据:', error.response.data)
          console.error('错误状态码:', error.response.status)
          ElMessage.error(`${dialogType.value === 'add' ? '添加' : '更新'}出错: ${error.response.status} - ${error.response.data?.message || error.message || '未知错误'}`)
        } else if (error.request) {
          console.error('未收到响应:', error.request)
          ElMessage.error(`${dialogType.value === 'add' ? '添加' : '更新'}出错: 服务器未响应`)
        } else {
          console.error('错误:', error.message)
          ElMessage.error(`${dialogType.value === 'add' ? '添加' : '更新'}出错: ${error.message || '未知错误'}`)
        }
      }
    }
  })
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.post('/springbootyyh3w/weishengjiancha/delete', [row.id], {
        headers: {
          'Token': localStorage.getItem('Token'),
          'Content-Type': 'application/json'
        }
      })
      
      if (response.data.code === 0) {
        ElMessage.success('删除成功')
        getInspectionList()
      } else {
        ElMessage.error(response.data.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除出错', error)
      ElMessage.error('删除出错')
    }
  }).catch(() => {})
}

// 分页处理
const handleSizeChange = (val) => {
  limit.value = val
  getInspectionList()
}

const handleCurrentChange = (val) => {
  page.value = val
  getInspectionList()
}

// 根据评分获取标签类型
const getScoreTagType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 80) return 'info'
  if (score >= 60) return 'warning'
  return 'danger'
}
</script>

<style scoped>
.inspection-container {
  padding: 20px;
}

.inspection-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-options {
  display: flex;
  align-items: center;
  gap: 20px;
}

.el-checkbox {
  margin-right: 10px;
}

.filter-container {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 